<template>
  <div class="app-container">
    <el-page-header @back="handleBack" content="修改规格属性模板" />
    <el-form
      ref="productSpecTemplateRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="mt-4">
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="模板描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="模板排序" prop="sort">
        <el-input v-model="form.sort" placeholder="请输入模板排序" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="1">启用</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 新增：模板属性关系列表 -->
      <el-form-item label="规格属性">
        <el-card
          v-for="(spec, index) in data.templateForm.specs"
          :key="index"
          class="spec-card">
          <div slot="header" class="clearfix">
            <span>规格 {{ index + 1 }}</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="removeSpec(index)">
              删除
            </el-button>
          </div>

          <el-form-item label="属性名称">
            <el-input v-model="spec.name" placeholder="如：Color"></el-input>
          </el-form-item>

          <el-form-item label="属性类型">
            <el-select v-model="spec.type" placeholder="请选择属性类型">
              <el-option label="售卖属性" :value="0"></el-option>
              <el-option label="基础属性" :value="1"></el-option>
              <el-option label="Overview属性" :value="2"></el-option>
              <el-option label="体积重量属性" :value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="可选值">
            <el-tag
              v-for="tag in spec.valuesJsonList"
              :key="tag"
              closable
              @close="removeValue(index, tag)">
              {{ tag }}
            </el-tag>
            <el-input
              v-if="spec.inputVisible"
              v-model="spec.inputValue"
              ref="saveTagInput"
              size="small"
              class="input-new-tag"
              @keyup.enter.native="addValue(index)"
              @blur="addValue(index)" />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(index)">
              + 添加值
            </el-button>
          </el-form-item>

          <el-form-item label="SKU影响">
            <el-switch
              v-model="spec.isSku"
              :active-value="1"
              :inactive-value="0"></el-switch>
          </el-form-item>

          <el-form-item label="允许自定义">
            <el-switch
              v-model="spec.isCustom"
              :active-value="1"
              :inactive-value="0"></el-switch>
          </el-form-item>

          <el-form-item label="单位">
            <el-input v-model="spec.unit" placeholder="如：mm、kg"></el-input>
          </el-form-item>

          <el-form-item label="排序">
            <el-input-number v-model="spec.sort" :min="0"></el-input-number>
          </el-form-item>
        </el-card>

        <el-button type="primary" icon="el-icon-plus" @click="addSpec">
          添加规格属性
        </el-button>
      </el-form-item>
    </el-form>

    <div class="mt-4" style="text-align: right">
      <el-button @click="handleBack">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </div>
</template>

<script setup name="ProductSpecTemplateEdit">
import {
  getProductSpecTemplate,
  getProductSpecTemplateDetail,
  updateProductSpecTemplate,
} from "@/api/product/productSpecTemplate";
import { listProductSpec } from "@/api/product/productSpec";
import { useRouter, useRoute } from "vue-router";
import { onMounted, ref, reactive, getCurrentInstance, nextTick } from "vue";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const productSpecTemplateRef = ref(null);
const productSpecList = ref([]);
const form = reactive({
  id: null,
  name: null,
  description: null,
  status: "1",
  sort: null,
  relationList: [],
});
const data = reactive({
  templateForm: {
    name: "",
    description: "",
    specs: [],
  },
});
const saveTagInputRefs = ref([]);

const rules = {
  name: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
};
function removeSpec(index) {
  data.templateForm.specs.splice(index, 1);
}
function addValue(specIndex) {
  const spec = data.templateForm.specs[specIndex];
  const inputValue = spec.inputValue;
  if (inputValue) {
    spec.valuesJsonList.push(inputValue);
    // 更新 JSON 字符串
    spec.valuesJson = JSON.stringify(spec.valuesJsonList);
  }
  spec.inputVisible = false;
  spec.inputValue = "";
}
function showInput(specIndex) {
  const spec = data.templateForm.specs[specIndex];
  spec.inputVisible = true;
  nextTick(() => {
    // 确保 DOM 已更新后再聚焦
    if (saveTagInputRefs.value[specIndex]) {
      saveTagInputRefs.value[specIndex].focus();
    }
  });
}
function addSpec() {
  data.templateForm.specs.push({
    name: "",
    type: 0,
    valuesJsonList: [],
    valuesJson: "[]", // 用于后端传输的 JSON 字符串
    isSku: 0,
    isCustom: 0,
    unit: "",
    sort: 0,
    inputVisible: false,
    inputValue: "",
  });
}
/** 初始化表单数据 */
function initForm() {
  const id = route.params.id;
  getProductSpecTemplateDetail(id).then((response) => {
    const res = response.data;
    form.id = res.id;
    form.name = res.name;
    form.description = res.description;
    form.status = res.status.toString(); // 确保是字符串类型
    form.sort = res.sort;

    // 处理关联列表数据
    // form.relationList =
    //   data.templateForm.specs.length > 0
    //     ? data.templateForm.specs.map((item) => ({
    //         ...item,
    //         productSpecId: item.productSpecId?.toString(),
    //         isRequired: item.isRequired?.toString() || "0",
    //         sort: item.sort || 0,
    //       }))
    //     : [{ productSpecId: null, sort: 0, isRequired: "0" }];
    data.templateForm.specs = res.specs;
  });
}

/** 查询商品规格属性列表 */
function getProductSpecList() {
  const queryParams = {
    pageSize: 9999,
  };
  listProductSpec(queryParams).then((response) => {
    productSpecList.value = response.rows;
  });
}

/** 添加属性关系 */
function addRelation() {
  // 若已添加所有可用规格，则提示无法继续添加
  if (form.relationList.length >= productSpecList.length) {
    proxy.$modal.msgWarning("已添加所有可用规格属性，无法继续添加");
    return;
  }
  form.relationList.push({
    productSpecId: null,
    sort: 0,
    isRequired: "0",
  });
}
/** 检查规格属性是否已存在 */
function checkSpecExists(specId, currentItem) {
  return form.relationList.some((item) => {
    // 跳过当前正在编辑的行，只检查其他行
    if (item === currentItem) return false;
    // 检查其他行是否有相同的specId
    return item.productSpecId === specId;
  });
}
/** 删除属性关系 */
function removeRelation(index) {
  form.relationList.splice(index, 1);
}

/** 处理规格属性变更 */
function handleSpecChange(item) {
  const currentSpecId = item.productSpecId;
  // 检查是否重复选择
  if (currentSpecId && checkSpecExists(currentSpecId, item)) {
    proxy.$modal.msgError("该规格属性已添加，请选择其他属性");
    // 重置当前选择
    item.productSpecId = null;
    return;
  }
  // 原排序逻辑保留
  if (!item.sort) {
    item.sort = form.relationList.length;
  }
}

/** 提交表单 */
function submitForm() {
  proxy.$refs.productSpecTemplateRef.validate((valid) => {
    if (valid) {
      // 处理提交数据格式：过滤掉未选择属性的关系项
      const submitData = {
        ...form,
        status: Number(form.status),
        sort: form.sort ? Number(form.sort) : null,
        // 核心修改：过滤空属性项，只保留有productSpecId的项
        specs: data.templateForm.specs
          .filter(
            (item) => item.productSpecId !== null && item.productSpecId !== ""
          ) // 过滤空值
          .map((item) => ({
            ...item,
            productSpecId: Number(item.productSpecId),
            sort: item.sort ? Number(item.sort) : 0,
            isRequired: Number(item.isRequired),
            templateId: form.id,
          })),
      };

      // 额外校验：确保至少保留一个有效属性（可选，根据业务需求）
      if (submitData.specs.length === 0) {
        proxy.$modal.msgError("请至少选择一个规格属性");
        return;
      }

      updateProductSpecTemplate(submitData).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        handleBack();
      });
    }
  });
}

/** 返回列表页面 */
function handleBack() {
  const obj = { path: "/product/spec-template" };
  proxy.$tab.closeOpenPage(obj);
}

// 初始化表单数据
onMounted(() => {
  initForm();
  getProductSpecList();
});
</script>

<style scoped>
.relation-list-container {
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  padding: 10px;
}

.relation-list-header {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
  font-weight: bold;
}

.header-item {
  text-align: left;
  padding: 0 10px;
}

.relation-list-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #e5e7eb;
}

.relation-list-item:last-child {
  border-bottom: none;
}

.list-item {
  padding: 0 10px;
}

.add-relation-btn {
  text-align: right;
}
.spec-card {
  margin-bottom: 20px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
